package net.zjitc.homework.hw2;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author Administrator
 * @Date 2020/5/22 8:49
 * 通过Servlet完成将图片展示在页面上
 **/
@WebServlet("/beauty")
public class Beauty extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /* 1、获取请求参数（filename），得知要展示的图片名
        *  2、根据图片名，获得图片存放的真实路径realPath
        *  3、通过输入流读取图片
        *     通过输出流将图片展示在页面上 */
        String filename = req.getParameter("filename");
        System.out.println(filename);
        /* 获取图片的真实路径：
           通过ServletContext对象（代表整个web应用）
        * */
        ServletContext servletContext = req.getServletContext();
        String realPath = servletContext.getRealPath("/img/"+filename);
        System.out.println(realPath);
        /* 通过字节输入流读取文件，响应的字节输出流写数据到页面*/
        FileInputStream fis=new FileInputStream(realPath);
        ServletOutputStream outputStream = resp.getOutputStream();
        /* 每次读写一个字节数组*/
        byte[] bytes=new byte[1024*2];
        int len=0;
        /* 若没有读取到文件末尾（-1）就一直读取，*/
        while ((len=fis.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
        fis.close();


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
